package heven.holt.wan.android.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import heven.holt.wan.android.model.ArticleModel
import heven.holt.wan.android.repository.WanArticleRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.mapLatest

/**
 * important!!!
 * 当flow在ViewModel中必须为成员变量时（Fragment加入回退栈不重新初始化变量），
 * 此种方案为手动传输cid到ViewModel初始化对象，这种方案必须实现ViewModelProvider.Factory
 * 另一种方案利用savedStateHandle自动获取Fragment的arguments
 * @see ProjectArticleViewModel
 */
class SystemArticleViewModel @AssistedInject constructor(
    private val wanArticleRepository: WanArticleRepository,
    @Assisted("cid") cid: Int
) : ViewModel() {

    private val currentCidStateFlow: MutableStateFlow<Int> =
        MutableStateFlow(cid)

    val flow: Flow<PagingData<ArticleModel>> = currentCidStateFlow.mapLatest {
        wanArticleRepository.getArticleProjectListFlow(it)
    }.flatMapLatest { it }.cachedIn(viewModelScope)
}